package com.rankeiot.platform.controller;

import com.rankeiot.core.data.MenuItem;
import com.rankeiot.core.data.response.PageResp;
import com.rankeiot.core.data.response.Resp;
import com.rankeiot.core.inner.argumet.QueryPage;
import com.rankeiot.core.util.CollectionUtil;
import com.rankeiot.core.MenuManager;
import com.rankeiot.platform.domain.Role;

import com.rankeiot.platform.domain.RolePermission;
import com.rankeiot.platform.domain.User;
import com.rankeiot.platform.domain.UserRole;
import com.rankeiot.platform.service.RoleService;
import com.rankeiot.core.anno.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.sagacity.sqltoy.model.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import java.util.*;

/**
 * 角色管理
 * <p>
 * generated by palmboot
 **/
@Tag(name = "角色管理")
@Auth
@RestController
@RequestMapping("role")
@RequiredArgsConstructor
public class RoleController {

    final RoleService roleService;
    final SqlToyLazyDao dao;

    @Operation(summary = "新增角色")
    @PostMapping("add")
    public Resp add(@Valid @RequestBody Role role) {
        dao.save(role);
        return Resp.ok();
    }

    @Operation(summary = "删除角色")
    @PostMapping("delete")
    @Transactional
    public Resp delete(@RequestBody List<Role> roles) {
        // dao.loadAll(roles);
        List<String> roleList = CollectionUtil.map(roles,role -> role.getSn());
        dao.deleteAll(roles);
        //删除相关权限
        dao.executeSql("delete from t_role_permission where role in (:roles)",new String[]{"roles"},new Object[]{roleList});
        //删除用户授权
        dao.executeSql("delete from t_user_role where role in (:roles)",new String[]{"roles"},new Object[]{roleList});
        return Resp.ok();
    }

    @Operation(summary = "更新角色")
    @PostMapping("save")
    public Resp save(@Valid @RequestBody Role role) {
        dao.update(role,"roleType","scope");
        return Resp.ok();
    }

    @Operation(summary = "获取角色")
    @GetMapping("detail")
    public Resp<Role> detail(String sn) {
        Role test=new Role();
        Role role = dao.load(new Role(sn));
        return Resp.of(role);
    }

    @Operation(summary = "获取角色列表")
    @PostMapping("list")
    public Resp<List<Role>> list(Role query) {
        List<Role> result = dao.findBySql("select * from t_role where #[and (role_type is null or role_type=:roleType)]", query);
        return Resp.of(result);
    }

    @Operation(summary = "获取机构的角色列表")
    @GetMapping("roleOfBranch")
    public Resp<List> roleOfBranch(String branch) {
        Map params=new HashMap();
        params.put("branchId",branch);
        List result = dao.findBySql("select * from t_role where role_type is null #[OR role_type = (select type from t_branch where sn=:branchId)]", params,Map.class);
        return Resp.of(result);
    }
    @Operation(summary = "保存角色权限")
    @PostMapping("save_role_permission/{role}")
    @Transactional
    public Resp saveRolePermission(@PathVariable String role,@RequestBody List<String> permissions) {
        RolePermission query = new RolePermission();
        query.setRole(role);
        //删除已有权限
        List<RolePermission> rp = dao.findBySql("select * from t_role_permission where role=:role", query);
        dao.deleteAll(rp);

        //保存新的权限
        if (permissions.size() > 0) {
            List<RolePermission> newPermissions = CollectionUtil.map(permissions, it -> new RolePermission(role, it));
            dao.saveAll(newPermissions);
        }

        return Resp.ok();
    }

    @Operation(summary = "获得全部权限树")
    @GetMapping("all_permission")
    public Resp<List<MenuItem>> allPermission() {
        return Resp.of(MenuManager.allPermission());
    }

    @Operation(summary = "获取角色管理列表")
    @GetMapping("role_permission")
    public Resp<Set<String>> rolePermissions(String role) {
        return Resp.of(roleService.getPermissionOfRole(role));
    }
    @Operation(summary = "获取含有指定用户角色用户列表")
    @PostMapping("user_in_role")
    public PageResp<User> userInRole(QueryPage query) {
        User user=new User();
        user.setRole(query.getStr("role"));
        Page<User> result = dao.findPageBySql(query.page(), "user_in_role", user);
        return Resp.of(result);
    }
    @Operation(summary = "获取没有对应角色用户列表")
    @PostMapping("user_not_in_role")
    public PageResp<User> userNotInRole(QueryPage query) {

        User user=new User();
        user.setRole(query.getStr("role"));

        Page<User> result = dao.findPageBySql(query.page(), "user_not_in_role", user);
        return Resp.of(result);
    }
    @Operation(summary = "删除角色用户")
    @PostMapping("remove_users")
    public Resp removeUsers(String role,List<String> users) {
        List<UserRole> userRoles=  CollectionUtil.map(users, userName->new UserRole(userName,role));
        dao.deleteAll(userRoles);
        return Resp.ok();
    }
    @Operation(summary = "往角色中添加用户")
    @PostMapping("add_users")
    public Resp addUsers(String role,List<String> users) {

       List<UserRole> userRoles=  CollectionUtil.map(users,userName->new UserRole(userName,role));
       // users.forEach(it->it.setRole(role));
        dao.saveAll(userRoles);
        return Resp.ok();
    }
}
